import express from 'express'
import fs from 'fs'
import { handleUrl } from '../../../util/index.js'
import { addSql, getResult } from '../../../util/operateSql.js'
import { arrayUpload, avatarUpload } from './config.js'

var router = express.Router();
const TABLE = 'robot.files'

var y = new Date().getFullYear()
var m = new Date().getMonth() + 1

const fileUpload = async (files) => {
  try {
    const data = mulcallback(files)
    const msg = data
  
    data.forEach(async (e,index) => {
      const {filepath:url,...rest} = e
      const sql = addSql(TABLE,{url,...rest})
      await getResult(sql)
    })
    return Promise.resolve(msg)
  } catch (error) {
    return Promise.reject(error)
  }
}

router.post('/base64ToFiles',(req,res,next) => {
  let {datas} = req.body
  
  try {
    datas = JSON.parse(datas)
    let msg = []
    Array.isArray(datas) && datas?.forEach(async e => {
      const file = dataURLtoFile(e.url,e.name)
      msg.push(await fileUpload(file))
    })
    res.json(req.app.locals.success(msg))

  } catch (error) {
    
    res.json(req.app.locals.error(error))
  }
})

/**
 * description: 文件列表上传(多字段模式)
 */
router.post('/files', arrayUpload, async (req, res, next) => {
  if (req.files) {
      const msg = await fileUpload(req.files)
      res.json(req.app.locals.success(msg))
  } else {
    res.json(req.app.locals.error('空文件'))
  }
})

/**
 * description:  单个文件上传(单字段模式)
 */
router.post('/', avatarUpload, (req, res, next) => {
  if (req.file.length > 0) {
      const data = callback(req.file)
      const msg = req.app.locals.success(data)
      res.json(msg)
  } else {
    res.json(req.app.locals.error())
  }
})

/**
 * base64转图片
 * @param {*} dataurl 
 * @param {*} filename 
 * @returns 
 */
function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  return fs.readFileSync([u8arr], filename, {type:mime});
}

/**
 * 单字段文件处理
 * @param {*} files 
 * @returns 
 */
 const callback = (files) => {
  return files.map(({originalname, path, size, mimetype}) => {
    return {
          filename,
          originalname: originalname,
          url: handleUrl(process.env.UPLOAD_HOST +(process.env.PREFIX  || '/file') + `\/${y}-${m>9?m:'0'+m}\/` + filename),
          size,
          mimetype,
          fieldname
      }
  })
}

/**
 * 多字段文件文件
 * @param {*} files 
 * @returns 
 */
const mulcallback = (files) => {
  let handleFiles = []
  for (const filedname in files) {
    handleFiles.push(...files[filedname].map(({originalname, size, mimetype,filename,fieldname}) => {
      return {
          filename,
          originalname: originalname,
          url: handleUrl(process.env.UPLOAD_HOST + process.env.PREFIX + `\/${y}-${m>9?m:'0'+m}\/` + filename),
          size,
          mimetype,
          fieldname
      }
    }))
  }
  return handleFiles
}

export default router;
